package com.baorant.springdemo1.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.*;

@RestController
public class FileController {

    // 指定上传目录（可配置到application.properties）
    private final Path rootLocation = Paths.get("uploads");

    /**
     * 文件下载接口
     */
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            // 创建上传目录（如果不存在）
            if (!Files.exists(rootLocation)) {
                Files.createDirectories(rootLocation);
            }

            // 保存文件
            Path destination = rootLocation.resolve(
                            Paths.get(file.getOriginalFilename()))
                    .normalize().toAbsolutePath();

            // 安全检查：防止路径遍历攻击
            if (!destination.getParent().equals(rootLocation.toAbsolutePath())) {
                throw new RuntimeException("不能存储在指定目录外");
            }

            Files.copy(file.getInputStream(), destination,
                    StandardCopyOption.REPLACE_EXISTING);

            return "上传成功: " + file.getOriginalFilename();
        } catch (IOException e) {
            throw new RuntimeException("上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/download/{filename}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        try {
            Path file = rootLocation.resolve(filename).normalize();
            Resource resource = new UrlResource(file.toUri());

            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION,
                                "attachment; filename=\"" + resource.getFilename() + "\"")
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);
            } else {
                throw new RuntimeException("文件不存在或不可读");
            }
        } catch (Exception e) {
            throw new RuntimeException("下载失败: " + e.getMessage());
        }
    }
}
